﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Xml.Linq;
using StartupSolution.ViewModel;
using Infragistics.Controls.Menus;

namespace StartupSolution.Views.Menus.BuildingDataTree
{
    public partial class DataTreeXaml : Page
    {
        public DataTreeXaml()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Sample_Loaded);
		}

		void Sample_Loaded(object sender, RoutedEventArgs e)
		{
		     LoadXMLData();
        }

        /// <summary> 
        /// This method will load data from a XML document and populate it as XamGrid ItemSource
        /// </summary>
        private void LoadXMLData()
        {
            // 	Loads the XML file and creates a XDocument object
            XDocument doc = XDocument.Load("Datasource/Books.xml");

            // Run LINQ query to retrieve the necessary data
        

				var dataSource = (from d in doc.Descendants("book")
								  where (d.Descendants("chapter") != null && d.Descendants("chapter").Count() > 0)
								  select new Book
								  {
									  Author = d.Attribute("Author").Value,
									  Title = d.Attribute("Title").Value,
									  Chapters = this.GetChapters(d)
								  });

				this.MyTree.ItemsSource = dataSource.ToList();
				
			}

		private IEnumerable<Chapter> GetChapters(XElement parent)
		{
			return (from d in parent.Descendants("chapter")
					select new Chapter
					{
						Title = d.Attribute("Title").Value
					}).ToList<Chapter>();
		}

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
    }


}